package com.gsmr.controller;

import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import com.gsmr.entity.Group;
import com.gsmr.entity.PageBean;
import com.gsmr.entity.Train_info;
import com.gsmr.service.GroupService;
import com.gsmr.service.MemberShipService;
import com.gsmr.service.Train_infoService;
import com.gsmr.service.Train_infoService;
import com.gsmr.util.ExcelUtil;
import com.gsmr.util.FormatDate;
import com.gsmr.util.Md5Util;
import com.gsmr.util.PropertityUtil;
import com.gsmr.util.ResponseUtil;
import com.gsmr.util.StringUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * @author 作者 : 黄志新
 * @version 创建时间：2017年8月11日 上午12:13:57 类说明：Train_infoController层
 */
@Controller
@RequestMapping("/train_info")
public class Train_infoController {

	@Resource
	private Train_infoService train_infoService;

	/**
	 * 分页条件查询Train_info
	 */
	@RequestMapping("/list")
	public void list(@RequestParam(value = "page", required = false) String page,
			@RequestParam(value = "rows", required = false) String rows, Train_info s_train_info, HttpServletResponse response)
			throws Exception {
		PageBean pageBean = new PageBean(Integer.parseInt(page), Integer.parseInt(rows));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		map.put("start", pageBean.getStart());
		map.put("size", pageBean.getPageSize());
		List<Train_info> train_infoList = train_infoService.find(map);
		Long total = train_infoService.getTotal(map);
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(train_infoList);
		result.put("rows", jsonArray);
		result.put("total", total);
		ResponseUtil.write(response, result);
	}


	/**
	 * 添加或者修Train_info
	 * @param flag 1 添加 2修改
	 */
	@RequestMapping("/save")
	public String save(Train_info train_info, HttpServletResponse response, Integer flag) throws Exception {
		int resultTotal = 0; // 操作的记录条数
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		map.put("MSISDN", train_info.getMSISDN());
		map.put("IMSI", train_info.getIMSI());
		map.put("CTCS_ID", train_info.getCTCS_ID());
		map.put("ENGINE_ID", train_info.getENGINE_ID());
		map.put("TrainId", train_info.getTrainId());
		if (flag == 1) {
			resultTotal = train_infoService.add(map);
		} else {
			resultTotal = train_infoService.update(map);
		}
		JSONObject result = new JSONObject();
		if (resultTotal > 0) {
			result.put("success", true);
		} else {
			result.put("success", false);
		}
		ResponseUtil.write(response, result);
		return null;
	}

	/**
	 * 删除Train_info
	 */
	@RequestMapping("/delete")
	public String delete(@RequestParam(value = "trainIds") String ids, HttpServletResponse response) throws Exception {
		String[] idsStr = ids.split(",");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		for (int i = 0; i < idsStr.length; i++) {
			map.put("TrainId", idsStr[i]);
			train_infoService.delete(map);
		}
		JSONObject result = new JSONObject();
		result.put("success", true);
		ResponseUtil.write(response, result);
		return null;
	}

	/**
	 * 判断是否存在指定用户名
	 */
	@RequestMapping("/existTrainId")
	public String existTrainId(String TrainId, HttpServletResponse response) throws Exception {
		JSONObject result = new JSONObject();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		map.put("TrainId", TrainId);
		if (train_infoService.findByTrainId(map) == null) {
			result.put("exist", false);
		} else {
			result.put("exist", true);
		}
		ResponseUtil.write(response, result);
		return null;
	}

	/**
	 * 导出Train_info
	 */
	@RequestMapping("/export")
	public String export(@RequestParam(value = "trainIds") String ids, HttpServletResponse response) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Workbook wb = new HSSFWorkbook();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		String headers[] = { "TrainId", "MSISDN", "IMSI", "CTCS_ID", "ENGINE_ID" };

		List<String> idsList = Arrays.asList(ids.split(","));
		
		if (ids != null && !ids.equals("null") && ids.length() > 0) {
			map.put("TrainIds", idsList);
		} else {
			map.put("TrainId", null);
		}
		List<Train_info> train_infoList = train_infoService.findByTrainIds(map);
		try {
			ExcelUtil.fillExcelData_Train_info(train_infoList, wb, headers);
			ResponseUtil.export(response, wb, "导出Train_Info" + FormatDate.formatDate() + ".xls");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 用模板导出Train_info
	 */
	@RequestMapping("/exportByTemplate")
	public void exportByTemplate(@RequestParam(value = "trainIds") String ids, HttpServletResponse response)
			throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		if (ids != null && !ids.equals("null") && !ids.equals("")) {
			List<String> idsList = Arrays.asList(ids.split(","));
			map.put("TrainIds", idsList);
			List<Train_info> train_infoList = train_infoService.findByTrainIds(map);
			try {
				Workbook wb = ExcelUtil.fillExcelDataWithTemplate_Train_info(train_infoList, "train_infoExportTemplate.xls");
				ResponseUtil.export(response, wb, "利用模版导出excel" + FormatDate.formatDate() + ".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			map.put("TrainIds", null);
			List<Train_info> train_infoList = train_infoService.findByTrainIds(map);
			try {
				Workbook wb = ExcelUtil.fillExcelDataWithTemplate_Train_info(train_infoList, "train_infoExportTemplate.xls");
				ResponseUtil.export(response, wb, "利用模版导出excel" + FormatDate.formatDate() + ".xls");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * Train_info上传
	 */
	@RequestMapping("/upload")
	public void upload(HttpServletRequest request, HttpServletResponse response, Integer uploadFlag) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("database_name", PropertityUtil.GSMR_DATABASE);
		map.put("TrainId", "0 OR 1=1");
		if (uploadFlag == 2) {
			int flag = train_infoService.delete(map);
		}
		// 将当前上下文初始化给 CommonsMutipartResolver （多部分解析器）
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		// 检查form中是否有enctype="multipart/form-data"
		if (multipartResolver.isMultipart(request)) {
			// 将request变成多部分request
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			// 获取multiRequest 中所有的文件名
			Iterator iter = multiRequest.getFileNames();

			while (iter.hasNext()) {
				// 一次遍历所有文件
				MultipartFile file = multiRequest.getFile(iter.next().toString());
				if (file != null) {
//					String path = PropertityUtil.UPLOAD_PATH + FormatDate.formatDate() + file.getOriginalFilename();
					//String path = file.getOriginalFilename();
					String path = "已导入" + new Date().getTime() + file.getOriginalFilename();
					// 上传
					File newFile = new File(path);
					file.transferTo(newFile);
					// 写数据进数据库
					POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(newFile));
					newFile.delete();
					HSSFWorkbook wb = new HSSFWorkbook(fs);
					HSSFSheet hssfSheet = wb.getSheetAt(0); // 获取第一个Sheet页
					JSONObject result = new JSONObject();
					try {
						if (hssfSheet != null) {
							for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
								HSSFRow hssfRow = hssfSheet.getRow(rowNum);
								if (hssfRow == null) {
									continue;
								}
								String id = ExcelUtil.formatCell(hssfRow.getCell(0));
								if (StringUtil.isEmpty(id)) {
									continue;
								}
								map.put("TrainId", ExcelUtil.getIntegerPart(id));
								map.put("MSISDN", ExcelUtil.getIntegerPart(ExcelUtil.formatCell(hssfRow.getCell(1))));
								map.put("IMSI", ExcelUtil.getIntegerPart(ExcelUtil.formatCell(hssfRow.getCell(2))));
								map.put("CTCS_ID", ExcelUtil.getIntegerPart(ExcelUtil.formatCell(hssfRow.getCell(3))));
								map.put("ENGINE_ID", ExcelUtil.getIntegerPart(ExcelUtil.formatCell(hssfRow.getCell(4))));
								train_infoService.add(map);
							}
						}
						result.put("success", true);
					} catch (Exception e) {
						result.put("success", false);
						e.printStackTrace();
					}
					ResponseUtil.write(response, result);
				}
			}
		}
	}
}